import os
from google.appengine.ext.webapp import template
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app

import tweepy
import datetime

import oauth

__author__ = 'jnmoses@gmail.com (Joe Moses)'

port = os.environ['SERVER_PORT']
if port and port != '80':
  HOST_NAME = '%s:%s' % (os.environ['SERVER_NAME'], port)
else:
  HOST_NAME = os.environ['SERVER_NAME']
  

consumer_key = ""
consumer_secret = ""
callback_url = ""

client = oauth.TwitterClient(consumer_key, consumer_secret, callback_url)

class MainPage(webapp.RequestHandler): 
    def get(self, mode=""):
        # Your application Twitter application ("consumer") key and secret.
        # You'll need to register an application on Twitter first to get this
        # information: http://www.twitter.com/oauth
        application_key = "" 
        application_secret = ""  
        
        # Fill in the next 2 lines after you have successfully logged in to 
        # Twitter per the instructions above. This is the *user's* token and 
        # secret. You need these values to call the API on their behalf after 
        # they have logged in to your app.
        user_token = "FILL_IN"  
        user_secret = "FILL_IN"
        
        # In the real world, you'd want to edit this callback URL to point to your
        # production server. This is where the user is sent to after they have
        # authenticated with Twitter. 
        callback_url = "%s/verify" % self.request.host_url 
    
        client = oauth.TwitterClient(application_key, application_secret, callback_url)
    
        if mode == "login":
          return self.redirect(client.get_authorization_url())
          
        if mode == "verify":
          auth_token = self.request.get("oauth_token")
          auth_verifier = self.request.get("oauth_verifier")
          user_info = client.get_user_info(auth_token, auth_verifier=auth_verifier)
          return self.response.out.write(user_info)
          
        if mode == "timeline":
          timeline_url = "http://twitter.com/statuses/user_timeline.xml"
          result = client.make_request(url=timeline_url, token=user_token, secret=user_secret)
          return self.response.out.write(result.content)
        
        self.response.out.write("<a href='/login'>Login via Twitter</a>")
        
        #set values to display
#        template_values = {         
#            'sample': 'sample'
#        }
        
        #get the template to display
 #       path = os.path.join(os.path.dirname(__file__), 'templates/index.html')
        #display the template with the values
#        self.response.out.write(template.render(path, template_values))  
        
    def post(self):
        #set values to display
        template_values = {         
            'twitteruser': self.request.get('username'),
            'utcoffset': self.request.get('utcoffset'),
            'host': HOST_NAME
        }
        
        #get the template to display
        path = os.path.join(os.path.dirname(__file__), 'templates/download.html')
        #display the template with the values
        self.response.out.write(template.render(path, template_values))
        
class UserTimelineiCal(webapp.RequestHandler):
    def get(self,screen_name):        
        self.response.headers['Content-Type'] = 'text/calendar'
        #self.response.headers['Content-Type'] = 'text/plain'
        
        #max count is 200
        user_tweets = tweepy.api.user_timeline(screen_name=screen_name,count=200)
        
        if self.request.get('utcoffset'):
            utcoffset = datetime.timedelta(hours=int(self.request.get('utcoffset')))
        else:
            utcoffset = datetime.timedelta(hours=0)
        
        self.response.out.write("BEGIN:VCALENDAR\r\n")
        self.response.out.write("PRODID:-//Alpha Code Monkey//Twitter Calender//EN\r\n")
        self.response.out.write("VERSION:2.0\r\n")
                
        for status in user_tweets: 
            adjusted_date = status.created_at + utcoffset
            status_text = status.text.replace("\r","").replace("\n","").replace(",","\,").replace(";","\;")
            
            self.response.out.write("BEGIN:VEVENT\r\n")
            self.response.out.write("UID:" + str(status.id) + "\r\n")
            self.response.out.write("DTSTAMP:" + adjusted_date.strftime("%Y%m%dT%H%M%SZ") + "\r\n")
            self.response.out.write("CREATED:" + adjusted_date.strftime("%Y%m%dT%H%M%SZ") + "\r\n")
            self.response.out.write("DTSTART:" + adjusted_date.strftime("%Y%m%dT%H%M%SZ") + "\r\n")
            self.response.out.write("SUMMARY:" + status_text + "\r\n")
            self.response.out.write("DESCRIPTION:" + status_text + " from " + status.source + "\r\n")
            self.response.out.write("URL:" + "http://twitter.com/" + screen_name + "/status/" + str(status.id) + "\r\n")
            self.response.out.write("END:VEVENT\r\n")
            
            #other VEVENT properties
            #class, last-mod, location, organizer, priority, seq, status, transp, recurid, dtend, duration
            #attach, attendee, categories, comment, contact, exdate, exrule, rstatus, related, resources, rdate, rrule, x-prop 
            
            #other Twitter status properties
            #status.truncated
            #status.in_reply_to_status_id
            #status.in_reply_to_user_id
            #status.favorited
            #status.in_reply_to_screen_name
            #stauts.user{}        
        
        self.response.out.write("END:VCALENDAR")

application = webapp.WSGIApplication([
    ('/(.*)', MainPage),
    ('/(.*).ics', UserTimelineiCal)
],debug=True)

def main():
    run_wsgi_app(application)

if __name__ == "__main__":
    main()
